package com.csdn.freemarker;


import com.csdn.chain.InvokeResult;
import com.csdn.chain.TestContext;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class Test {
    private static final Configuration conf = new Configuration(Configuration.VERSION_2_3_20);

    static {
        StringTemplateLoader templateLoader = new StringTemplateLoader();
        conf.setTemplateLoader(templateLoader);
    }

    public static void main(String[] args) throws Exception {
        String body = "{\"head\":{\"dept\":\"${HeadDept}\"}}";
        StringTemplateLoader templateLoader = (StringTemplateLoader) conf.getTemplateLoader();
        templateLoader.putTemplate("test", body);
        Template template = conf.getTemplate("test");
        Map<String, Object> param = new HashMap<>();
        param.put("HeadDept", "aaaaaaaa");
        StringWriter stringWriter = new StringWriter();
        template.process(param, stringWriter);
        System.out.println(stringWriter.toString());
        //函数接口声明
        ExecutorTask<InvokeResult> executorTask = () -> test();
        // InvokeResult result = executorTask.excute();
        //异步调用声明函数方法
        InvokeResult result = async(executorTask, new TestContext());
        System.out.println(result);
    }

    public static InvokeResult async(ExecutorTask<InvokeResult> executorTask, TestContext testContext) throws ExecutionException, InterruptedException {

        return CompletableFuture.supplyAsync(() -> {
            return executorTask.excute();
        }).whenComplete((invokeResult, throwable) -> {
            if (throwable != null) {
                throw new RuntimeException("执行异常");
            }
        }).get();
    }

    public static InvokeResult test() {
        return new InvokeResult("SUCCESS");
    }


}
